package com.qiangesoft.blog.file.controller;

import com.qiangesoft.blog.common.result.ResponseResult;
import com.qiangesoft.blog.file.model.FileInfoVo;
import com.qiangesoft.blog.file.service.ISysFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文件管理
 *
 * @author qiange
 * @date 2023-04-23
 */
@Slf4j
@Api(tags = "文件管理")
@RestController
@RequestMapping("/file")
public class SysFileInfoController {

    @Autowired
    private ISysFileInfoService fileInfoService;

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public ResponseResult<FileInfoVo> upload(@RequestParam(value = "file") MultipartFile file, @RequestParam(required = false) String category) {
        try {
            FileInfoVo fileInfoVo = fileInfoService.uploadFileByPath(file, category);
            return ResponseResult.success(fileInfoVo);
        } catch (Exception e) {
            return ResponseResult.error("上传失败");
        }
    }

    @PostMapping("/batchUpload")
    @ApiOperation(value = "文件批量上传")
    public ResponseResult<List<FileInfoVo>> upload(@RequestParam(value = "files") MultipartFile[] files) {
        try {
            List<FileInfoVo> fileInfoVos = fileInfoService.batchUploadFile(files);
            return ResponseResult.success(fileInfoVos);
        } catch (Exception e) {
            return ResponseResult.error("上传失败");
        }
    }

    @GetMapping("/download/{fileId}")
    @ApiOperation(value = "单个下载")
    public void download(@PathVariable Long fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        fileInfoService.download(fileId, request, response);
    }

    @GetMapping("/{fileId}")
    @ApiOperation(value = "文件详情")
    public ResponseResult<FileInfoVo> getFileInfoById(@PathVariable Long fileId) {
        return ResponseResult.success(fileInfoService.getFileInfoById(fileId));
    }

    @DeleteMapping("/{fileId}")
    @ApiOperation(value = "删除文件")
    public ResponseResult deleteFileInfoById(@PathVariable Long fileId) {
        fileInfoService.removeById(fileId);
        return ResponseResult.success();
    }

    @GetMapping("/previewUrl")
    @ApiOperation(value = "预览地址")
    public ResponseResult<String> previewUrl(Long fileId) {
        FileInfoVo fileInfo = fileInfoService.getFileInfoById(fileId);
        return ResponseResult.success(fileInfo.getStoreUrl());
    }

}